#!/usr/bin/python3
import sys
import dep_graph.cache_view
from dep_graph.cache import FileBackedCachedGraph

def pprint_gen_rule(gen_rule):
  output = ['gen_rule(\n']
  output += ['  name = ', repr(gen_rule.key.basic_full_name()), ',\n']
  output += ['  cmd = ', repr(gen_rule.get_cmd()), ',\n']
  if gen_rule.get_env() is not None:
    output += ['  env = ', repr(gen_rule.get_env()), ',\n']

  for name in ['inp', 'out', 'meta', 'wipe']:
    fsets = list(getattr(gen_rule, name).getFsets())
    if fsets:
      output += ['  ', name, ' = [\n']
      first_fset = True
      fsets.sort(key=lambda fset: fset.key.name)
      for fset in fsets:
        name = fset.key.name
        if first_fset:
          first_fset = False
        else:
          output += [',\n']
        output += ['    ', name, ' = [']

        sorted_files = []
        for f in fset.files:
          sorted_files.append(repr(f))
        sorted_files.sort()

        sorted_deps = []
        for f in fset.dependencies:
          sorted_deps.append(f.key.fset_name())
        sorted_deps.sort()

        all_sorted = sorted_files + sorted_deps
        if all_sorted:
          output.append('\n      ')
          output.append(',\n      '.join(sorted_files + sorted_deps))
          output.append('\n    ]')
        else:
          output.append(']')
      output.append('\n  ],\n')
  output += ['  valid = ', str(gen_rule.get_valid()), '\n']
  output.append(')\n')
  return ''.join(output)

def dump_graph(graph, output):
  keys = set(graph.keys())
  graph_lines = []
  for key in list(keys):
    obj = graph.lookup(key)
    if isinstance(graph.lookup(key), dep_graph.cache_view.GenRule):
      graph_lines.append(pprint_gen_rule(obj))

  graph_lines.sort()

  output.write('\n'.join(graph_lines))

def main():
  graph = FileBackedCachedGraph(sys.argv[1])
  dump_graph(graph, sys.stdout)


if __name__ == '__main__':
  main()
